package com.ksvip.next.components.redis.filter;

import java.util.List;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Pipeline;

public class JedisFilter {

    private static final GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    private JedisPool                            jedisPool;

    public JedisFilter(JedisPool jedisPool) {
        if (jedisPool == null) {
            jedisPool = new JedisPool(poolConfig, "localhost", 6379);
        }
        this.jedisPool = jedisPool;
    }

    @FunctionalInterface
    public interface JedisExecutor<T> {
        T execute(Jedis jedis);
    }

    public <T> T execute(JedisExecutor<T> jedisExecutor) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedisExecutor.execute(jedis);
        }
    }

    @FunctionalInterface
    public interface PipelineExecutor {
        void load(Pipeline pipeline);
    }

    public List<Object> pipeline(List<PipelineExecutor> pipelineExecutors) {
        try (Jedis jedis = jedisPool.getResource()) {
            Pipeline pipeline = jedis.pipelined();
            for (PipelineExecutor executor : pipelineExecutors) {
                executor.load(pipeline);
            }
            return pipeline.syncAndReturnAll();
        }
    }
}
